package com.peoit.honeycomb.application.impl;

import java.util.ArrayList;
import java.util.List;

import javax.transaction.Transactional;

import org.springframework.stereotype.Service;

import com.peoit.honeycomb.application.FinanceReportApplication;
import com.peoit.honeycomb.domain.FinanceReport;
import com.peoit.honeycomb.domain.HoneycombProject;
import com.peoit.honeycomb.domain.exception.ProjectNotExistException;
import com.peoit.honeycomb.domain.exception.ReportDateExistException;
import com.peoit.honeycomb.domain.repository.HibernateEntityRepository;
import com.peoit.honeycomb.dto.FinanceReportDto;

@Service
public class FinanceReportApplicationImpl extends HibernateEntityRepository implements FinanceReportApplication {

	/**
	 * 发布财务报表
	 */
	@Override
	@Transactional
	public void publishReport(FinanceReportDto dto) {
		HoneycombProject project = find(HoneycombProject.class, dto.getProjectId());
		if (project == null) {
			throw new ProjectNotExistException();
		}
		String whereSql = " reportDate = ? and project.id = ?";
		Object[] queryParams = { dto.getDate(), dto.getProjectId() };
		FinanceReport report = queryByWhereSingle(FinanceReport.class, whereSql, queryParams);
		if (report != null) {
			throw new ReportDateExistException();
		}
		dto.setProject(project);
		this.create(FinanceReportDto.toEntity(dto));
	}

	@Override
	public List<FinanceReportDto> getProjectFinanceReport(String projectId) {
		String whereSql = " project.id = ? order by reportDate";
		Object[] queryParams = { projectId };
		List<FinanceReport> financeReports = queryByWhereList(FinanceReport.class, whereSql, queryParams);
		List<FinanceReportDto> result = new ArrayList<FinanceReportDto>();
		for (FinanceReport financeReport : financeReports) {
			result.add(FinanceReportDto.toDto(financeReport));
		}
		return result;
	}

}
